package artid.com.arttogo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.db.Selector;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.NoteBean;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.utils.DownloadUtil;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.VioceUtils;

public class CatalogueDetailsActivity extends Activity implements OnClickListener,
        OnFocusChangeListener, OnEditorActionListener {
    private WebView wv;
    private TextView tuID1, tuID2;
    private EditText note1, note2;
    private ImageView voice, delete, back, share;
    private RelativeLayout llNote;
    private LinearLayout notetwo;
    private String id = "4";
    private int type = 0;
    private String imageurl, surl, content;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.webview);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setDefaultTextEncodingName("UTF-8");
        tuID1 = (TextView) findViewById(R.id.tv_tulu1);
        tuID2 = (TextView) findViewById(R.id.tv_tulu2);
        notetwo = (LinearLayout) findViewById(R.id.ll_note_two);
        llNote = (RelativeLayout) findViewById(R.id.ll_note);
        note1 = (EditText) findViewById(R.id.et_note1);
        note2 = (EditText) findViewById(R.id.et_note2);
        voice = (ImageView) findViewById(R.id.iv_voice);
        delete = (ImageView) findViewById(R.id.iv_delete);
        back = (ImageView) findViewById(R.id.back_btn);
        share = (ImageView) findViewById(R.id.iv_share);
        delete.setOnClickListener(this);
        llNote.setOnClickListener(this);
        back.setOnClickListener(this);
        share.setOnClickListener(this);
        id = getIntent().getStringExtra("id");
        imageurl = getIntent().getStringExtra("imageurl");
        surl = getIntent().getStringExtra("surl");
        content = getIntent().getStringExtra("content");

        // wv.getSettings().setUseWideViewPort(true);
        // wv.getSettings().setLoadWithOverviewMode(true);
        // wv.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        // wv.loadUrl("file:///android_asset/pdfBook/index.html");
        wv.addJavascriptInterface(new JavaScriptInterface(), "android");
        //
        type = getIntent().getIntExtra("type", 0);
//         wv.loadUrl("http://119.253.34.22:11180/bookTemp2/mobile/");
        if (type == DownloadUtil.NOTE_OFFLINE) {

            DbManager db = x.getDb(((ArtToGoApp) getApplication()).getDaoConfig());
            try {
                Selector<NoteBean> selector = db.selector(NoteBean.class);
                // 如果要使用条件查询的话可以使用
                // Selector<user> selector =
                // db.selector(User.class).where("id","=",id).and("age",">",10);
                List<NoteBean> all = selector.findAll();
                if (all != null) {
                    for (int i = 0; i < all.size(); i++) {
                        mynote.put(all.get(i).getId(), all.get(i).getContent());
                    }
                } else {
                    all = new ArrayList<NoteBean>();
                }
                System.out.println("all=" + all.toString());
            } catch (DbException e) {
                System.out.println("save failure:" + e.getMessage());
            }
            llNote.setVisibility(View.GONE);
            wv.loadUrl("file:///" + getIntent().getStringExtra("url"));
        } else if (type == DownloadUtil.NOTE_ONLINE) {
            requstMyNote("1");
            wv.loadUrl(getIntent().getStringExtra("url"));
        }
    }

    public void jumpNote(String json) {

    }

    public class JavaScriptInterface {

        /**
         * Instantiate the interface and set the context
         */
        public JavaScriptInterface() {

        }

        // {"currentPageIndex":"15","id":"3","title":"春江泛舟·行书","pagenumber":"123","a":"shoucang"}

        /**
         * Show a toast from the web page
         */
        @JavascriptInterface
        public void jumpNote(String json) {
            // Toast.makeText(CatalogueDetailsActivity.this, "js调用了jumpNote函数传递参数：" + json,
            // Toast.LENGTH_SHORT).show();
            Log.i("TAG", "调用成功==================》》》》》" + json);
            try {
                JSONObject ob = new JSONObject(json);
                // System.out.println(ob.toString());
                if (ob != null) {
                    String star = ob.optString("a");
                    if (star.equals("-2")) {
                        Toast.makeText(CatalogueDetailsActivity.this, "只有拍品才能写笔记哦",
                                Toast.LENGTH_SHORT).show();
                        return;
                    } else if (star.equals("-1")) {
                        Toast.makeText(CatalogueDetailsActivity.this, "只有拍品才能收藏哦",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (star.equals("biji")) {
                        String number = ob.optString("pagenumber");
                        String sid = ob.optString("id");

                        Message msg = new Message();
                        Bundle data = new Bundle();
                        data.putString("number", number);
                        data.putString("id", sid);
                        msg.setData(data);
                        handler.sendMessage(msg);

                        // showBottomPopupWindow(wv, number);
                    } else if (star.equals("shoucang")) {
                        String sid = ob.optString("id");
                        if (sid.contains("-")) {
                            String[] s = sid.split("-");
                            requstColl(s[0]);
                            requstColl(s[1]);
                        } else {
                            requstColl(sid);
                        }
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    VioceUtils v;
    String noteId;

    public void noteShow(String number, String id) {
        llNote.setVisibility(View.VISIBLE);
        v = new VioceUtils(CatalogueDetailsActivity.this, voice);
        v.init();
        v.setEd(note1);
        noteId = id;
        if (number.contains("-")) {
            String[] s1 = number.split("-");
            String[] s2 = id.split("-");
            tuID1.setText("Lot:"+s1[0]);
            note1.setText(getNote(s2[0]));
            tuID2.setText("Lot:"+s1[1]);
            note2.setText(getNote(s2[1]));
            notetwo.setVisibility(View.VISIBLE);
        } else {
            tuID1.setText("Lot:"+number);
            note1.setText(getNote(id));
            notetwo.setVisibility(View.GONE);
        }
        note1.setOnFocusChangeListener(this);
        note2.setOnFocusChangeListener(this);
        note1.setOnEditorActionListener(this);
        note2.setOnEditorActionListener(this);
    }

    private String getNote(String id) {
        for (String key : mynote.keySet()) {
            if (id.equals(key))
                return mynote.get(key);
        }
        return "";
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.iv_delete:
                note1.setText("");
                note2.setText("");
                break;
            case R.id.ll_note:
                llNote.setVisibility(View.GONE);
                break;
            case R.id.back_btn:
                finish();
                break;
            case R.id.iv_share:
//                Toast.makeText(CatalogueDetailsActivity.this, "分享ID获取失败", Toast.LENGTH_LONG).show();
                AppUtil.shareOR(this, "四海集珍专场图录", content, imageurl, surl);
                break;

            default:
                break;
        }
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        // TODO Auto-generated method stub
        if (hasFocus) {
            // 获得焦点
            v.setEd((EditText) view);
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // TODO Auto-generated method stub
        /* 判断是否是“GO”键 */
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            /* 隐藏软键盘 */
            InputMethodManager imm = (InputMethodManager) v.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
            }
            if (type == DownloadUtil.NOTE_OFFLINE) {

                DbManager db = x.getDb(((ArtToGoApp) getApplication()).getDaoConfig());
                try {
                    if (noteId.contains("-")) {
                        String[] s1 = noteId.split("-");
                        NoteBean nb1 = new NoteBean(s1[0], note1.getText()
                                .toString());
                        mynote.put(s1[0], note1.getText().toString());
                        NoteBean nb2 = new NoteBean(s1[1], note2.getText()
                                .toString());
                        mynote.put(s1[1], note2.getText().toString());
                        db.save(nb1);
                        db.save(nb2);
                    } else {
                        NoteBean nb = new NoteBean(noteId, note1.getText()
                                .toString());
                        mynote.put(noteId, note1.getText().toString());
                        db.save(nb);
                    }
                    System.out.println("创建数据表");

                    // CatalogueBean cata = new CatalogueBean();
                    // cata.setId(1);
                    // cata.setProgress(String.valueOf(22));
                    // db.update(cata, "progress");

                    Selector<NoteBean> selector = db.selector(NoteBean.class);
                    // 如果要使用条件查询的话可以使用
                    // Selector<user> selector =
                    // db.selector(User.class).where("id","=",id).and("age",">",10);
                    List<NoteBean> all = selector.findAll();
                    System.out.println("all=" + all.toString());
                } catch (DbException e) {
                    System.out.println("save failure:" + e.getMessage());
                }
                llNote.setVisibility(View.GONE);
            } else if (type == DownloadUtil.NOTE_ONLINE) {
                requstNote(noteId);
            }
            // edittext.setText("success");
            // webview.loadUrl(URL);

            return true;
        }
        return false;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String number = data.getString("number");
            String sid = data.getString("id");
            noteShow(number, sid);
            // TODO
            // UI界面的更新等相关操作
        }
    };

    // 同步数据库笔记到服务器
    public void requstNotes(List<NoteBean> all) {

        RequestParams params = new RequestParams(Cache.baseUrl
                + "Lot/onlineNote");
        params.addHeader("Accept", "application/json, text/javascript, */*");
        try {
            // params.addParameter("pagesize", 2);
            JSONArray a = new JSONArray();
            for (int i = 0; i < all.size(); i++) {
                JSONObject o = new JSONObject();
                o.put("id", all.get(i).getId());
                o.put("content", all.get(i).getContent());
                a.put(o);
            }
            params.addBodyParameter("data", a.toString());
            params.addBodyParameter("token", "16999fabc9badd35142b5aae3c76e88e");
            params.addBodyParameter("type", "2");
            System.out.println(params.toString());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        x.http().get(params, new CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException cex) {
                // TODO Auto-generated method stub
                System.out.println("主动停止网络请求");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // TODO Auto-generated method stub
                // 请求错误
            }

            @Override
            public void onFinished() {
                // TODO Auto-generated method stub
                System.out.println("请求完毕,不管成功失败");
            }

            @Override
            public void onSuccess(String result) {
                // TODO Auto-generated method stub
                // 成功
                result = NetUtils.decodeUnicode(result);
                System.out.println("result=" + result);
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject baseOb = new JSONObject(result);
                        String msg = baseOb.optString("msg");
                        String ret = baseOb.optString("ret");
                        if (ret.equals("1")) {
                            if (noteId.contains("-")) {
                                String[] no = noteId.split("\\-");
                                mynote.put(no[0], note1.getText().toString());
                                mynote.put(no[1], note2.getText().toString());
                            } else {
                                mynote.put(noteId, note1.getText().toString());
                            }
                            // for (int i = 0; i < no.length; i++) {

                            // }
                            Toast.makeText(CatalogueDetailsActivity.this, "笔记保存成功", 2)
                                    .show();
                        } else {
                            Toast.makeText(CatalogueDetailsActivity.this, msg, 2).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                llNote.setVisibility(View.GONE);
                note1.setText("");
                note2.setText("");

            }
        });
    }

    // 发送笔记
    public void requstNote(String id) {

        RequestParams params = new RequestParams(Cache.baseUrl
                + "Lot/onlineNote");
        params.addHeader("Accept", "application/json, text/javascript, */*");
        try {
            // params.addParameter("pagesize", 2);
            JSONArray a = new JSONArray();
            if (id.contains("-")) {
                String[] s1 = id.split("-");
                JSONObject o1 = new JSONObject();
                o1.put("id", s1[0]);
                o1.put("content", note1.getText().toString());
                // o1.put("type", "2");
                String noteString = note2.getText().toString();
                a.put(o1);
                if (!TextUtils.isEmpty(noteString)) {
                    JSONObject o2 = new JSONObject();
                    o2.put("id", s1[1]);
                    o2.put("content", note2.getText().toString());
                    // o2.put("type", "2");
                    a.put(o2);
                }
            } else {
                JSONObject o = new JSONObject();
                o.put("id", id);
                o.put("content", note1.getText().toString());
                // o.put("type", "2");
                a.put(o);
            }

            params.addBodyParameter("data", a.toString());
            params.addBodyParameter("token", "16999fabc9badd35142b5aae3c76e88e");
            params.addBodyParameter("type", "2");
            System.out.println(params.toString());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        x.http().get(params, new CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException cex) {
                // TODO Auto-generated method stub
                System.out.println("主动停止网络请求");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // TODO Auto-generated method stub
                // 请求错误
            }

            @Override
            public void onFinished() {
                // TODO Auto-generated method stub
                System.out.println("请求完毕,不管成功失败");
            }

            @Override
            public void onSuccess(String result) {
                // TODO Auto-generated method stub
                // 成功
                result = NetUtils.decodeUnicode(result);
                System.out.println("result=" + result);
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject baseOb = new JSONObject(result);
                        String msg = baseOb.optString("msg");
                        String ret = baseOb.optString("ret");
                        if (ret.equals("1")) {
                            if (noteId.contains("-")) {
                                String[] no = noteId.split("\\-");
                                mynote.put(no[0], note1.getText().toString());
                                mynote.put(no[1], note2.getText().toString());
                            } else {
                                mynote.put(noteId, note1.getText().toString());
                            }
                            // for (int i = 0; i < no.length; i++) {

                            // }
                            Toast.makeText(CatalogueDetailsActivity.this, "笔记保存成功", 2)
                                    .show();
                        } else {
                            Toast.makeText(CatalogueDetailsActivity.this, msg, 2).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                llNote.setVisibility(View.GONE);
                note1.setText("");
                note2.setText("");

            }
        });
    }

    private Map<String, String> mynote = new HashMap<String, String>();

    // 获得我的专场笔记
    public void requstMyNote(String id) {

        RequestParams params = new RequestParams(Cache.baseUrl
                + "special/userLotnote");
        params.addHeader("Accept", "application/json, text/javas cript, */*");
        params.addBodyParameter("id", id);
        params.addBodyParameter("token", "16999fabc9badd35142b5aae3c76e88e");
        System.out.println(params.toString());
        x.http().get(params, new CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException cex) {
                // TODO Auto-generated method stub
                System.out.println("主动停止网络请求");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // TODO Auto-generated method stub
                // 请求错误
            }

            @Override
            public void onFinished() {
                // TODO Auto-generated method stub
                System.out.println("请求完毕,不管成功失败");
            }

            @Override
            public void onSuccess(String result) {
                // TODO Auto-generated method stub
                // 成功
                result = NetUtils.decodeUnicode(result);
                System.out.println("result=" + result);
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject baseOb = new JSONObject(result);
                        String msg = baseOb.optString("msg");
                        String ret = baseOb.optString("ret");
                        if (ret.equals("1")) {
                            mynote.clear();
                            JSONArray notearr = baseOb.optJSONArray("data");
                            for (int i = 0; i < notearr.length(); i++) {
                                JSONObject noteOb = notearr.optJSONObject(i);
                                mynote.put(noteOb.optString("id"),
                                        noteOb.optString("memo"));
                            }
                        } else {
                            Toast.makeText(CatalogueDetailsActivity.this, msg, 2).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    // 我的收藏
    public void requstColl(String id) {

        RequestParams params = new RequestParams(Cache.baseUrl
                + "Jigou/addCollection");
        params.addHeader("Accept", "application/json, text/javascript, */*");
        params.addBodyParameter("contentid", id);
        params.addBodyParameter("inform_type", "4");
        params.addBodyParameter("type", "1");
        params.addBodyParameter("token", "16999fabc9badd35142b5aae3c76e88e");
        x.http().post(params, new CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException cex) {
                // TODO Auto-generated method stub
                System.out.println("主动停止网络请求");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // TODO Auto-generated method stub
                // 请求错误
            }

            @Override
            public void onFinished() {
                // TODO Auto-generated method stub
                System.out.println("请求完毕,不管成功失败");
            }

            @Override
            public void onSuccess(String result) {
                // TODO Auto-generated method stub
                // 成功
                result = NetUtils.decodeUnicode(result);
                System.out.println("result=" + result);
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject baseOb = new JSONObject(result);
                        String msg = baseOb.optString("msg");
                        String ret = baseOb.optString("ret");
                        if (ret.equals("1")) {
                            Toast.makeText(CatalogueDetailsActivity.this, "收藏成功", 2).show();
                        } else {
                            Toast.makeText(CatalogueDetailsActivity.this, msg, 2).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });
    }

}
